<?php
session_start();
require_once '../config/database.php';

if (!is_admin()) {
    header('Content-Type: application/json');
    echo json_encode(['success' => false, 'message' => 'Unauthorized']);
    exit;
}

if (isset($_POST['brand_name'])) {
    $database = new Database();
    $db = $database->getConnection();
    
    // Check if brand already exists
    $check_query = "SELECT id FROM brands WHERE LOWER(name) = LOWER(?)";
    $check_stmt = $db->prepare($check_query);
    $check_stmt->execute([trim($_POST['brand_name'])]);
    
    if ($existing = $check_stmt->fetch()) {
        echo json_encode(['success' => true, 'brand_id' => $existing['id']]);
        exit;
    }
    
    // Add new brand
    $query = "INSERT INTO brands (name) VALUES (?)";
    $stmt = $db->prepare($query);
    
    if ($stmt->execute([trim($_POST['brand_name'])])) {
        echo json_encode([
            'success' => true,
            'brand_id' => $db->lastInsertId()
        ]);
    } else {
        echo json_encode(['success' => false, 'message' => 'Failed to add brand']);
    }
} 